﻿namespace ClassyBlog.DataAccess
{
    using System;
    using System.Collections.Generic;
    using System.IO;
    using System.Linq;

    using DomainObjects;
    using Infrastructure;

    public class PostRepository : IPostRepository
    {
        public PostRepository(
            string dataDirectory,
            IPathResolver resolver,
            IArticleFactory<Post> factory)
        {
            if (string.IsNullOrWhiteSpace(dataDirectory))
            {
                throw new ArgumentException(
                    TextMessages.Repository_Ctor_Data_Directory_Blank,
                    "dataDirectory");
            }

            if (resolver == null)
            {
                throw new ArgumentNullException("resolver");
            }

            if (factory == null)
            {
                throw new ArgumentNullException("factory");
            }

            PathResolver = resolver;
            Factory = factory;
            DataPath = Path.Combine(dataDirectory, "posts");
        }

        protected string DataPath { get; private set; }

        protected IPathResolver PathResolver { get; private set; }

        protected IArticleFactory<Post> Factory { get; private set; }

        public virtual Post FindOne(string slug)
        {
            var absolutePath = PathResolver.Resolve(DataPath, slug);

            if (string.IsNullOrWhiteSpace(absolutePath))
            {
                return null;
            }

            var post = Factory.Create(DataPath, absolutePath);

            return post;
        }

        public virtual IEnumerable<Post> All()
        {
            var posts = PathResolver.ResolveAll(DataPath, null)
                                    .Select(absolutePath =>
                                        Factory.Create(DataPath, absolutePath))
                                    .Where(post =>
                                        post != null &&
                                        post.PublishedAt <= Clock.UtcNow())
                                   .AsQueryable();

            return posts;
        }
    }
}